package main.java.com.waylau.netty.demo.privateprotocol.server;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import main.java.com.waylau.netty.demo.privateprotocol.struct.Header;
import main.java.com.waylau.netty.demo.privateprotocol.struct.NettyMessage;
import main.java.com.waylau.netty.demo.privateprotocol.util.MessageType;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.fastjson.JSON;

/**
 * @author Lilinfeng
 * @date 2014年3月15日
 * @version 1.0
 * SimpleChannelInboundHandler
 */
public class LoginAuthRespHandler extends SimpleChannelInboundHandler<Object> {

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		super.channelRegistered(ctx);
	}

	/**
	 * 保存用户是否登录
	 */
	private Map<String, Boolean> nodeCheck = new ConcurrentHashMap<>();
	private String[] whitekList = { "127.0.0.1", "192.168.1.104", "localhost" };
	@Override
	public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		NettyMessage message = JSON.parseObject((String) msg, NettyMessage.class);
		// 如果是握手请求消息，处理，其它消息透传
		if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
			String nodeIndex = ctx.channel().remoteAddress().toString();
			NettyMessage loginResp = null;
			// 重复登陆，拒绝
			if (nodeCheck.containsKey(nodeIndex)) {
				loginResp = buildResponse((byte) -1);
			} else {
				InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
				String ip = address.getAddress().getHostAddress();
				boolean isOK = false;
				for (String WIP : whitekList) {
					if (WIP.equals(ip)) {
						isOK = true;
						break;
					}
				}
				loginResp = isOK ? buildResponse((byte) 0) : buildResponse((byte) -1);
				if (isOK)
					nodeCheck.put(nodeIndex, true);
			}
			System.out.println("登录响应 : " + loginResp + " body [" + loginResp.getBody() + "]");
			ctx.writeAndFlush(JSON.toJSONString(loginResp));
		} else {
			ctx.fireChannelRead(msg);
		}
	}


	private NettyMessage buildResponse(byte result) {
		NettyMessage message = new NettyMessage();
		Header header = new Header();
		header.setType(MessageType.LOGIN_RESP.value());
		message.setHeader(header);
		message.setBody(result);
		return message;
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
		Channel incoming = ctx.channel();
		System.out.println("channelInactive:"+incoming.remoteAddress()+"掉线");
	}
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		nodeCheck.remove(ctx.channel().remoteAddress().toString());// 删除缓存
		ctx.close();
		ctx.fireExceptionCaught(cause);
	}
}
